<?php

namespace App\Jobs;

use App\Http\Logic\OrderLogic;
use App\Logic\GoodsLogic;
use App\Models\SwtBjMachine;
use App\Models\SwtOrder;
use App\Services\TuoYuanService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Queue\SerializesModels;

class RecognitionVideo implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $order_id;

    public $tries = 8;
    /**
     * CancelOrder constructor.
     * @param $id
     */
    public function __construct($id)
    {
        $this -> order_id = $id;
    }

    public function middleware()
    {
        return [(new WithoutOverlapping($this->order_id))->dontRelease()];
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        echo "发生回调任务，订单号：". $this->order_id ."\n";

        $order_info = SwtOrder::with(['bj_open'])->firstWhere('id', $this -> order_id);

        $machine_info = SwtBjMachine::firstWhere('machine_id', $order_info -> machine_id);

        try {
            $machine_goods = GoodsLogic::getDoorGoods($order_info -> machine_id);

            //货柜内没有商品时取消订单
            if(!$machine_goods) {
                OrderLogic::cancelOrder($order_info -> order_sn, $order_info -> door_num, $order_info -> platform);
                return;
            }

            $goods = [];

            foreach($machine_goods as $v) {
                $goods[] = [
                    'num'   => $v['weight'],
                    'price' => (float) bcdiv($v['sell_price'], 100, 2),
                    'skuId' => $v['goods']['bar_code']
                ];
            }

            $videos = [
                ['url' => $order_info -> bj_open -> video_main_url],
                ['url' => $order_info -> bj_open -> video_auxiliary_url]
            ];

            $res = TuoYuanService::setVideoInfo($order_info -> order_sn, $videos, $goods, $machine_info->imei);

            echo "请求结果：".json_encode($res, 256)."\n";

            $order_info -> video_status = 1;

            $order_info -> save();

            echo "完成回调任务，订单号：". $this->order_id ."\n";
        } catch (\Exception $e) {
            echo "任务失败：".$e->getMessage(). $this->order_id ."\n";

            $this->fail($e -> getMessage());
        }
    }
}
